package com.demo.study.thread.compalteFuture;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 异步编程 代码例子 CompletableFuture
 */
public class CompletableFutureTest {

    public static void main(String[] args) {
        // 模拟多个接口调用
        List<CompletableFuture<String>> futures = Arrays.asList(
                CompletableFuture.supplyAsync(() -> getResultFromInterface1()),
                CompletableFuture.supplyAsync(() -> getResultFromInterface2()),
                CompletableFuture.supplyAsync(() -> getResultFromInterface3())
        );

        // 使用CompletableFuture.allOf等待所有接口调用完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                futures.toArray(new CompletableFuture[0])
        );

        // 当所有接口调用完成后，收集结果到一个List
        CompletableFuture<List<String>> combinedFuture = allFutures
                .thenApply(v ->
                        futures.stream()
                                .map(CompletableFuture::join)
                                .collect(Collectors.toList())
                );

        // 等待结果并打印
        combinedFuture.thenAccept(results -> {
            System.out.println("Combined results:");
            results.forEach(System.out::println);
        });

        // 防止主线程退出
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 模拟接口1返回结果
    private static String getResultFromInterface1() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Result from Interface 1";
    }

    // 模拟接口2返回结果
    private static String getResultFromInterface2() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Result from Interface 2";
    }

    // 模拟接口3返回结果
    private static String getResultFromInterface3() {
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Result from Interface 3";
    }
}
